package com.example.delicioushunter.view.activity;

import java.io.File;
import java.util.ArrayList;

import com.example.delicioushunter.R;
import com.example.delicioushunter.control.databasecontrol.BookControl;
import com.example.delicioushunter.control.databasecontrol.FoodControl;
import com.example.delicioushunter.model.database.DHDatabaseHelper;
import com.example.delicioushunter.model.object.Book;
import com.example.delicioushunter.model.object.Food;
import com.example.delicioushunter.view.adapter.FoodAdapter;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class Foods_in_Book_Activity extends Activity {

	private static final int REQUEST_CODE_IMAGE_GALLERY = 0;
	private static final int REQUEST_CODE_CAMERA_CAPTURE = 1;
	private static final int REQUEST_CODE_CROP = 3;
	protected static final int REQUEST_CODE_FOOD_ID = 4;
	/**
	 * Views
	 */
	private EditText editFoodName;
	private ImageView imgCancel, imgSave;
	private ListView listLeft, listCenter, listRight;

	/**
	 * Properties
	 */
	private FoodAdapter adapterLeft, adapterCenter, adapterRight;
	private ArrayList<Food> foodLeft, foodCenter, foodRight;
	private Context mContext;
	private int _id = 0;
	private SQLiteDatabase wdb;
	private SQLiteDatabase rdb;
	private DHDatabaseHelper helper;
	private Uri picUri;
	private int selected = 0;
	private int collumn = 0;
	private int index = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_foods_in__book_);

		editFoodName = (EditText) findViewById(R.id.editFoodName);
		imgCancel = (ImageView) findViewById(R.id.imgCancel);
		imgSave = (ImageView) findViewById(R.id.imgSave);

		listLeft = (ListView) findViewById(R.id.listLeft);
		listCenter = (ListView) findViewById(R.id.listCenter);
		listRight = (ListView) findViewById(R.id.listRight);

		imgCancel.setOnTouchListener(imgCancelTouch);
		imgSave.setOnTouchListener(imgSaveTouch);

		editFoodName.setVisibility(View.GONE);
		imgCancel.setVisibility(View.GONE);
		imgSave.setVisibility(View.GONE);

		foodLeft = new ArrayList<Food>();
		foodCenter = new ArrayList<Food>();
		foodRight = new ArrayList<Food>();

		adapterLeft = new FoodAdapter(mContext, foodLeft);
		adapterCenter = new FoodAdapter(mContext, foodCenter);
		adapterRight = new FoodAdapter(mContext, foodRight);

		listLeft.setAdapter(adapterLeft);
		listCenter.setAdapter(adapterCenter);
		listRight.setAdapter(adapterRight);
		listLeft.setOnItemClickListener(onLeftItemClick);
		listCenter.setOnItemClickListener(onCenterItemClick);
		listRight.setOnItemClickListener(onRightItemClick);

		Intent intent = this.getIntent();
		_id = Integer.parseInt(intent.getExtras().getString("ID"));
		helper = new DHDatabaseHelper(mContext);

		loadFood();
	}

	OnItemClickListener onLeftItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			listLeft.setClickable(false);
			Intent intent = new Intent(Foods_in_Book_Activity.this,
					EditFoodActivity.class);
			int _id = foodLeft.get(position).get_id();
			intent.putExtra("ID", String.valueOf(_id));
			selected = position;
			collumn = 1;
			startActivityForResult(intent, REQUEST_CODE_FOOD_ID);
		}
	};

	OnItemClickListener onCenterItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			listCenter.setClickable(false);
			Intent intent = new Intent(Foods_in_Book_Activity.this,
					EditFoodActivity.class);
			int _id = foodCenter.get(position).get_id();
			intent.putExtra("ID", String.valueOf(_id));
			selected = position;
			collumn = 2;
			startActivityForResult(intent, REQUEST_CODE_FOOD_ID);
		}
	};

	OnItemClickListener onRightItemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			listRight.setClickable(false);
			Intent intent = new Intent(Foods_in_Book_Activity.this,
					EditFoodActivity.class);
			int _id = foodRight.get(position).get_id();
			intent.putExtra("ID", String.valueOf(_id));
			selected = position;
			collumn = 3;
			startActivityForResult(intent, REQUEST_CODE_FOOD_ID);
		}
	};

	OnTouchListener imgCancelTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			editFoodName.setText(null);
			editFoodName.setVisibility(View.GONE);
			imgCancel.setVisibility(View.GONE);
			imgSave.setVisibility(View.GONE);
			return false;
		}
	};

	OnTouchListener imgSaveTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			String foodName = editFoodName.getText().toString();
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_food_thumb);
			bitmap = Bitmap.createScaledBitmap(bitmap, 244, 400, false);
			wdb = helper.getWritableDatabase();
			Food food = new Food();
			food.setBook_id(_id);
			food.setName(foodName);
			food.setThumb(bitmap);

			FoodControl control = new FoodControl();
			int lastId = control.addFood(food, wdb);
			bitmap.recycle();
			bitmap = null;
			Toast.makeText(mContext, "Successfully", Toast.LENGTH_SHORT).show();
			rdb = helper.getReadableDatabase();
			Food newfood = control.getFood(lastId, rdb);
			if (index == 1) {
				foodLeft.add(newfood);
				adapterLeft.notifyDataSetChanged();
				index = 2;
			} else if (index == 2) {
				foodCenter.add(newfood);
				adapterCenter.notifyDataSetChanged();
				index = 3;
			} else if (index == 3) {
				foodRight.add(newfood);
				adapterRight.notifyDataSetChanged();
				index = 1;
			}
			return false;
		}
	};

	private class LoadFoodTask extends
			AsyncTask<Void, Integer, ArrayList<Food>> {

		private ProgressDialog pd;

		@Override
		protected ArrayList<Food> doInBackground(Void... params) {
			try {
				rdb = helper.getReadableDatabase();
				FoodControl control = new FoodControl();
				ArrayList<Food> list = control.getAllFoodsOnBook(_id, rdb);
				return list;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<Food> result) {
			super.onPostExecute(result);
			foodLeft.clear();
			foodCenter.clear();
			foodRight.clear();

			for (Food food : result) {
				if (index == 1) {
					foodLeft.add(food);
					adapterLeft.notifyDataSetChanged();
					index = 2;
				} else if (index == 2) {
					foodCenter.add(food);
					adapterCenter.notifyDataSetChanged();
					index = 3;
				} else if (index == 3) {
					foodRight.add(food);
					adapterRight.notifyDataSetChanged();
					index = 1;
				}
			}

			result.clear();
			pd.dismiss();
		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(Foods_in_Book_Activity.this,
					R.style.MyDialogTheme);
			pd.setMessage("Loading..");
			pd.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

	}

	public void loadFood() {
		LoadFoodTask task = new LoadFoodTask();
		task.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.foods_in__book_, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_food:
			addFood();
			break;
		case R.id.action_title:
			updateTitle();
			break;
		case R.id.action_gallery:
			loadFromGallery();
			break;
		case R.id.action_capture:
			captureImage();
			break;
		case R.id.action_delete:
			deleteBook();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void addFood() {
		editFoodName.setVisibility(View.VISIBLE);
		imgCancel.setVisibility(View.VISIBLE);
		imgSave.setVisibility(View.VISIBLE);
	}

	private void updateTitle() {
		final Dialog dialog = new Dialog(mContext, android.R.style.Theme_DeviceDefault_InputMethod);
		dialog.setContentView(R.layout.dialog_edit_title);
		dialog.setTitle("Edit Book Title");

		final BookControl control = new BookControl();

		rdb = helper.getReadableDatabase();
		final Book book = control.getBook(_id, rdb);
		final EditText editTitle = (EditText) dialog
				.findViewById(R.id.editTitle);
		editTitle.setText(book.getBook_title());
		ImageView imgCancel = (ImageView) dialog.findViewById(R.id.imgCancel);
		imgCancel.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				dialog.dismiss();
				return false;
			}
		});

		ImageView imgSave = (ImageView) dialog.findViewById(R.id.imgSave);
		imgSave.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				book.setBook_title(editTitle.getText().toString());
				book.setImage(null);
				wdb = helper.getWritableDatabase();
				control.updateBook(book, wdb);
				Toast.makeText(mContext, "Update Successfully",
						Toast.LENGTH_SHORT).show();
				dialog.dismiss();
				return false;
			}
		});

		dialog.show();

	}

	private void loadFromGallery() {
		try {
			Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
			galleryIntent.setType("image/*");
			startActivityForResult(galleryIntent, REQUEST_CODE_IMAGE_GALLERY);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(mContext, "Cannot find gallery.", Toast.LENGTH_SHORT)
					.show();
			e.printStackTrace();
		}
	}

	private void captureImage() {
		try {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, REQUEST_CODE_CAMERA_CAPTURE);
		} catch (ActivityNotFoundException e) {
			Toast.makeText(mContext, "Cannot find camera.", Toast.LENGTH_SHORT)
					.show();
			e.printStackTrace();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_CANCELED) {
			if (collumn == 1) {
				foodLeft.remove(selected);
				adapterLeft.notifyDataSetChanged();
			} else if (collumn == 2) {
				foodCenter.remove(selected);
				adapterCenter.notifyDataSetChanged();
			} else if (collumn == 3) {
				foodRight.remove(selected);
				adapterRight.notifyDataSetChanged();
			}
		}

		if (resultCode == RESULT_OK) {
			if (data == null) {
				Toast.makeText(Foods_in_Book_Activity.this,
						"Cannot find the image", Toast.LENGTH_SHORT).show();
				return;
			}

			if (requestCode == REQUEST_CODE_CAMERA_CAPTURE) {
				picUri = data.getData();
				performCrop();
			}

			if (requestCode == REQUEST_CODE_IMAGE_GALLERY) {
				picUri = data.getData();
				performCrop();
			}

			if (requestCode == REQUEST_CODE_CROP) {
				Bundle extras = data.getExtras();
				Bitmap thePic = extras.getParcelable("data");
				Bitmap resize = Bitmap.createScaledBitmap(thePic, 180, 180,
						true);
				final BookControl control = new BookControl();
				rdb = helper.getReadableDatabase();
				final Book book = control.getBook(_id, rdb);
				wdb = helper.getWritableDatabase();
				book.setBook_title(null);
				book.setImage(resize);
				control.updateBook(book, wdb);
				Toast.makeText(mContext, "Update Successfully",
						Toast.LENGTH_SHORT).show();
			}

			if (requestCode == REQUEST_CODE_FOOD_ID) {
				int food_id = Integer.parseInt(data.getStringExtra("FOOD_ID"));
				FoodControl control = new FoodControl();
				rdb = helper.getReadableDatabase();
				Food food = control.getFood(food_id, rdb);
				if (collumn == 1) {
					foodLeft.set(selected, food);
					adapterLeft.notifyDataSetChanged();
				} else if (collumn == 2) {
					foodCenter.set(selected, food);
					adapterCenter.notifyDataSetChanged();
				} else if (collumn == 3) {
					foodRight.set(selected, food);
					adapterRight.notifyDataSetChanged();
				}
			}
		}
	}

	private void performCrop() {
		try {
			Intent cropIntent = new Intent("com.android.camera.action.CROP");
			cropIntent.setDataAndType(picUri, "image/*");
			cropIntent.putExtra("crop", "true");
			cropIntent.putExtra("aspectX", 1);
			cropIntent.putExtra("aspectY", 1);
			cropIntent.putExtra("outputX", 180);
			cropIntent.putExtra("outputY", 180);
			cropIntent.putExtra("scale", true);
			cropIntent.putExtra("return-data", true);
			startActivityForResult(cropIntent, REQUEST_CODE_CROP);
		} catch (ActivityNotFoundException anfe) {
			String errorMessage = "Whoops - your device doesn't support the crop action!";
			Toast toast = Toast
					.makeText(this, errorMessage, Toast.LENGTH_SHORT);
			toast.show();
		}
	}

	private void deleteBook() {
		File file;
		for (Food f : foodLeft) {
			if (!f.getInfo_spd_uri().equalsIgnoreCase("empty")) {
				file = new File(f.getInfo_spd_uri());
				if (file.exists())
					file.delete();
			}
		}
		for (Food f : foodCenter) {
			if (!f.getInfo_spd_uri().equalsIgnoreCase("empty")) {
				file = new File(f.getInfo_spd_uri());
				if (file.exists())
					file.delete();
			}
		}
		for (Food f : foodRight) {
			if (!f.getInfo_spd_uri().equalsIgnoreCase("empty")) {
				file = new File(f.getInfo_spd_uri());
				if (file.exists())
					file.delete();
			}
		}

		BookControl control = new BookControl();
		wdb = helper.getWritableDatabase();
		control.deleteBook(_id, wdb);
		Toast.makeText(mContext, "Delete Successfully", Toast.LENGTH_SHORT)
				.show();
		Intent data = new Intent();
		data.putExtra("BOOK_ID", String.valueOf(_id));
		setResult(RESULT_CANCELED, data);
		finish();
	}

	@Override
	public void onBackPressed() {
		Intent data = new Intent();
		data.putExtra("BOOK_ID", String.valueOf(_id));
		setResult(RESULT_OK, data);
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();
		listLeft.setClickable(true);
		listCenter.setClickable(true);
		listRight.setClickable(true);
	}
	
	

}
